<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 职工代表大会编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form
            :formList="formList"
            :form="form"
            :is-emit="false"
            :editModel="editModel == 0 ? '' : ''"
            @change="changeForm"
            @selectOrg="selectOrg" 
          >
            <template slot="winTheBidTime">
              <a-input disabled v-model="winTheBidTime"></a-input>
            </template>
            <!-- 附件上传 -->
            <template #fileList>
              <template v-if="editModel != 0&&!isDisabled">
                <l-table businessCode="BM28" :uploadArrys.sync="form.fileList"></l-table>
                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
              </template>
              <file-link v-else :fileList="form.fileList" style="margin-top: -3px"></file-link>
            </template>
            <template v-slot:table>
              <a-form-model-item class="mb20" label=" " :colon="false">
                <a-table
                  bordered
                  ref="table1"
                  size="default"
                  rowKey="key"
                  :columns="columns1"
                  :data-source="loadData1"
                  :alert="true"
                  :pagination="false"
                >
                <div
                  v-for="col in ['contractFee', 'notContractFee', 'contractFeeRate']"
                  :slot="col"
                  slot-scope="text, record"
                  :key="col"
                  class="form-item"
                >
                    <template v-if="editModel != 0">
                      <span v-if="col === 'contractFee'">{{ record[col] == undefined ? '无' : record[col] }}</span>

                      <BaseInputNumber v-else v-model="record[col]"
                                       class="requiredFormItem"
                                       :disabled="isDisabled"
                                       @change="changeTable1(record)" :precision="2" />
                    </template>
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </a-table>

                <a-table
                  bordered
                  ref="table2"
                  size="default"
                  rowKey="key"
                  :columns="columns2"
                  :data-source="loadData2"
                  :alert="true"
                  :pagination="false"
                >
                  <div
                    v-for="col in ['autoContractFee', 'notAutoContractFee', 'autoContractFeeRate']"
                    :slot="col"
                    slot-scope="text, record"
                    :key="col"
                    class="form-item"
                  >
                    <template v-if="editModel != 0">
                      <span v-if="col === 'autoContractFee'">{{
                        record[col] == undefined ? '无' : record[col]
                      }}</span>
                      <BaseInputNumber
                              class="requiredFormItem"
                        v-else
                        v-model="record[col]"
                        :disabled="isDisabled"
                        @change="changeTable2(record, col)"
                        :precision="2"
                      />
                    </template>
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                  </a-table
                >
              </a-form-model-item>
            </template>
          </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="风险金分配表"></title-name>
          <div v-if="editModel != 0" class="mb12">
            <!-- 导出 -->
            <excel class="ml12" ref="exportAll" fileName="风险金分配表" is-click-generate="false">
              <a-button
                type="primary"
                icon="download"
                slot="excelBtn"
                :disabled="form.riskFeeData.length == 0"
                @click="exportAll"
                >模板导出</a-button
              >
            </excel>
            <ExcelImportButton
              ref="excelImportButton"
              icon="import"
              button-text="数据导入"
              @handleSubmit="handleImport"
              v-if="editModel != 0&&!isDisabled"
            />
          </div>
          <div class="tip">
            导入操作步骤：1.点击添加行,完善员工姓名。2.点击模板导出，完善模板信息。3.导入完善后的数据
          </div>

          <!-- 表格 -->
          <s-table
            bordered
            ref="tableRisk"
            tableLayout="fixed"
            size="default"
            rowKey="id"
            :columns="editModel != '0' ? columns : columnsLook"
            :data="loadData"
            :alert="true"
            :showPagination="false"
          >
            <div
              v-for="col in ['code', 'idCard', 'name', 'planRiskFee', 'remark', 'riskRate']"
              :slot="col"
              slot-scope="text, record, index"
              :key="col"
              class="form-item"
            >
              <template>
                <!-- 该组件每次添加行的时候都会调用一次选项获取的接口，强烈建议修改成只获取一次 -->
                <div class="requiredFormItem">
                  <SelectPersonByProject
                          :key="index"
                          v-if="col === 'name'"
                          v-model="record.name"
                          noRepeatRequest
                          :disabled="editModel == 0 || isDisabled"
                          placeholder="请选择"
                          :isOrg="true"
                          :addJob="true"
                          :isEdit="editModel != '2'"
                          :userList="userList"
                          :show-search="true"
                          @personChanged="personChanged($event, record)"
                  />
                </div>
                <template v-if="editModel != 0">
                  <BaseInput v-if="col === 'idCard' || col === 'code'" v-model="record[col]" disabled></BaseInput>

                  <BaseInputNumber
                          class="requiredFormItem"
                    v-else-if="col === 'planRiskFee' || col === 'riskRate'"
                    v-model="record[col]"
                    :precision="2"
                    :disabled="editModel == 0 || isDisabled"
                    @blur="change(col)"
                  >
                  </BaseInputNumber>
                  <BaseInput
                    v-else-if="col === 'remark'"
                    :disabled="editModel == 0 || isDisabled"
                    v-model="record[col]"
                  >
                  </BaseInput>
                </template>
                <template v-else> {{ col === 'name' ? '' : text }}</template>
              </template>
            </div>
            <template slot="action" slot-scope="text, record, index">
              <span v-if="editModel != 0&&!isDisabled">
                <a-popconfirm title="确定要删除?" @confirm="() => del(record, index)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </template>
            <template v-if="editModel != 0&&!isDisabled" slot="footer"> <a @click="addLine">添加行</a> </template>
          </s-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="editModel != 0 && !isConsultation">
        <a-button
          v-if="form.status == 'REJECTED'"
          type="primary"
          :loading="loading.REJECTED"
          @click="handleSave('REJECTED')"
          >保存</a-button
        >
        <a-button
          :disabled="isAdd"
          v-else
          class="button_right"
          type="primary"
          :loading="loadingBtn.DRAFT"
          @click="handleSave('DRAFT')"
          >保存草稿</a-button
        >
        <!-- <a-button
                    
                    class="button_right"
                    type="primary"
                    :loading="loading.DRAFT"
                    @click="handleSave('DRAFT')"
                    >保存草稿</a-button
                > -->
          <!-- :disabled="isAdd" -->
        <a-button
          class="button_right"
          type="primary"
          :loading="loadingBtn.SUBMITTED"

          @click="handleSave('SUBMITTED')"
          >提交</a-button
        >
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
      <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
        <BasePrintButton
          class="button_right"
          v-if="!isAudit && form.status == 'PAST'"
          type="primary"
          :beforePrintFn="print"
        />
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { getTargetList, getTarget, addTarget, printTarget } from '@/api/businessAffairs/responsibilityManagement' // api
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import { getQuotationList } from '@/api/businessAffairs/priceSeparation'
import moment from 'moment'
import config from '@/config'
import { getOneOrgUsers } from '@/api/commons.js'
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '员工编号',
    dataIndex: 'code',
    scopedSlots: { customRender: 'code' }
  },
  {
    title: '风险金比率(%)',
    dataIndex: 'riskRate',
    scopedSlots: { customRender: 'riskRate' }
  },
  {
    title: '应预留风险金(元)',
    dataIndex: 'planRiskFee',
    scopedSlots: { customRender: 'planRiskFee' }
  },
  {
    title: '身份证号',
    dataIndex: 'idCard',
    scopedSlots: { customRender: 'idCard' }
  },
  {
    title: '备注',
    dataIndex: 'remark',
    scopedSlots: { customRender: 'remark' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '员工编号',
    dataIndex: 'code',
    scopedSlots: { customRender: 'code' }
  },
  {
    title: '风险金比率(%)',
    dataIndex: 'riskRate',
    scopedSlots: { customRender: 'riskRate' }
  },
  {
    title: '应预留风险金(元)',
    dataIndex: 'planRiskFee',
    scopedSlots: { customRender: 'planRiskFee' }
  },
  {
    title: '身份证号',
    dataIndex: 'idCard',
    scopedSlots: { customRender: 'idCard' }
  },
  {
    title: '备注',
    dataIndex: 'remark',
    scopedSlots: { customRender: 'remark' }
  }
]
const columns1 = [
  {
    title: '合同额（不含税）（元）',
    dataIndex: 'notContractFee',
    width: '33%',
    scopedSlots: { customRender: 'notContractFee' }
  },
  {
    title: '合同额（税金）（元）',
    dataIndex: 'contractFeeRate',
    width: '33%',
    scopedSlots: { customRender: 'contractFeeRate' }
  },
  {
    title: '合同额（含税）（元）',
    dataIndex: 'contractFee',
    scopedSlots: { customRender: 'contractFee' }
  }
]
const columns2 = [
  {
    title: '自施合同额（不含税）（元）',
    dataIndex: 'notAutoContractFee',
    width: '33%',
    scopedSlots: { customRender: 'notAutoContractFee' }
  },
  {
    title: '自施合同额（税金）（元）',
    dataIndex: 'autoContractFeeRate',
    width: '33%',
    scopedSlots: { customRender: 'autoContractFeeRate' }
  },
  {
    title: '自施合同额（含税）（元）',
    dataIndex: 'autoContractFee',
    scopedSlots: { customRender: 'autoContractFee' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonByProject
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    this.columns = columns
    this.columnsLook = columnsLook
    this.columns1 = columns1
    this.columns2 = columns2
    return {
      userList: [],
      loadData1: [
        {
          notContractFee: undefined,
          contractFeeRate: undefined,
          contractFee: undefined
        }
      ],

      loadData2: [
        {
          notAutoContractFee: undefined,
          autoContractFeeRate: undefined,
          autoContractFee: undefined
        }
      ],
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        riskFeeData: [],
        fillDate: '',
        fillPeopleName: '',
        completeTime: '',
        projectManagerName: '',
        reservedRiskFee: 0,
        tentativelyUpRate: '',
        projectDeptId: '',
        projectId:null,
        standardCostPofitRate:''
      }, // 表单
      winTheBidTime: '',
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        contractFee: [{ required: true, message: '请输入' }],
        autoContractFee: [{ required: true, message: '请输入' }],
        tentativelyUpProfitFee: [{ required: true, message: '请输入' }],
        tentativelyUpRate: [{ required: true, message: '请输入' }],
        constructionArea: [{ required: true, message: '请输入' }],
        contractQualityGoal: [{ required: true, message: '请输入' }],
        contractSaveGoal: [{ required: true, message: '请选择' }],
        contractBeginTime: [{ required: true, message: '请选择' }],
        contractEndTime: [{ required: true, message: '请选择' }],
        fileList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'change' }],
        signDate: [{ required: true, message: '请选择' }],
        standardCostPofitRate:[{ required: true, message: '请输入' }],
      }, // 校验规则
      init: false, // 初始化控件
      removeApi: { remove: {} }, // api
      key: 0,
      cacheData: {},
      editingKey: '',
      isAdd: false,
      loadData: () => {
        if (this.form.riskFeeData.length > 0) {
          return new Promise((resolve, reject) => {
            resolve({
              data: this.form.riskFeeData
            })
          })
        }
      },
      importCheck: {
        姓名: 'nameText',
        '风险金比率(%)': 'riskRate',
        '应预留风险金(元)': 'planRiskFee',
        备注: 'remark'
      },
      //获取流程配置值
        processConfig: null,
        //点击提交发送流程配置值
        setProcessConfig: null,
        businessId: null,
        isDisabled: false,
        projectOrgId: ''
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileList')
        })
      }
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
 async mounted() {
    this.$refs.exportAll?.tableToExcelFile(
      {
        columns: [
          { title: '姓名', dataIndex: 'nameText' },
          { title: '风险金比率(%)', dataIndex: 'riskRate' },
          { title: '应预留风险金(元)', dataIndex: 'planRiskFee' },
          { title: '备注', dataIndex: 'remark' }
        ]
      },
      0
    )
    if(this.isConsultation){
      this.$route.meta.title = '意见征询'
    }else{
      this.$route.meta.title = ['目标责任书查看', '目标责任书编辑', '目标责任书新增'][this.editModel]
    }
    if(this.$route.query.t==1) {
      // 补录
      this.isDisabled = true
    }
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      getTarget({ id: this.id })
        .then((res) => {
          this.loading = false
          res[1].data.riskFeeData = res[1].data.riskFeeData || []
          this.form = { ...this.form, ...this.$clone(res[1].data) }
          if(this.editModel == 1) {
            this.form.fillPeopleName = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
            this.form.fillDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
          }

          // form添加到表格

          this.$nextTick(() => {
            this.loadData1[0].notContractFee = this.form.notContractFee
            this.loadData1[0].contractFeeRate = this.form.contractFeeRate
            this.loadData1[0].contractFee = this.form.contractFee
            this.loadData2[0].notAutoContractFee = this.form.notAutoContractFee
            this.loadData2[0].autoContractFeeRate = this.form.autoContractFeeRate
            this.loadData2[0].autoContractFee = this.form.autoContractFee

            this.$refs.tableRisk.refresh(true)

            this.init = true
          })
          console.log(this.form)
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.form.fillPeopleName = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
      this.form.fillDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
      this.form.projectId = this.$userInfo().currentPost.projectId;
      this.$nextTick(() => {
        this.init = true
      })
    }
      //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_target_responsibility_letter_management')
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          checkStrictly: true,
          isQueryProjecDetail: false,
          rules: [{ required: true, message: '请选择所属单位', trigger: 'change' }],
          span:16,
          disabled: true,
          isNeedAuth: true
        },
        {
          keyName: 'completeTime',
          type: 'BaseInput',
          disabled: true,
          label: '应完成时间'
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        },
        {
          keyName: 'tentativelyUpProfitFee',
          type: 'BaseInputNumber',
          precision: 2,
          disabled: this.editModel == 0 || this.isDisabled,
          label: '暂定上缴利润额(万元)',
          change: (e) => {
            this.changeForm('tentativelyUpProfitFee')
          }
        },
        {
          keyName: 'tentativelyUpRate',
          type: 'BaseInputNumber',
          precision: 2,
          disabled: this.editModel == 0 || this.isDisabled,
          label: '上缴利润率%'
        },
        {
          keyName: 'constructionArea',
          type: 'BaseInputNumber',
          precision: 2,
          disabled: this.editModel == 0 || this.isDisabled,
          label: '建筑面积(m2)'
        },
        {
          keyName: 'standardCostPofitRate',
          type: 'BaseInputNumber',
          precision: 2,
          disabled: this.editModel == 0,
          label: '标准成本降低率%'
        },
        {
          keyName: 'signDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '签订日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'contractQualityGoal',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.isDisabled,
          label: '合同质量目标'
        },
        {
          keyName: 'contractSaveGoal',
          type: 'BaseInput',
          disabled: this.editModel == 0 || this.isDisabled,
          label: '合同安全目标'
        },
        {
          keyName: 'winTheBidTime',
          type: 'BaseInput',
          disabled: true,
          slot: true,
          label: '中标时间'
        },
        {
          keyName: 'contractBeginTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0 || this.isDisabled,
          label: '合同开工日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'contractEndTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0 || this.isDisabled,
          label: '合同竣工日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'projectManagerName',
          type: 'BaseInput',
          disabled: true,
          label: '项目经理'
        },
        {
          keyName: 'reservedRiskFee',
          type: 'BaseInputNumber',
          disabled: true,
          precision: 2,
          label: '预留风险金总额'
        },
        {
          keyName: 'fillPeopleName',
          type: 'a-input',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'fillDate',
          type: 'a-date-picker',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          slot: true,
          keyName: 'fileList',
          label: '*责任书电子版',
          span: 24
        }
      ]
    }
  },
  //    ;(record.code = $event.employeeNum),
  //                                             (record.nameText = $event.employeeName),
  //                                             (record.idCard = $event.idCard)
  methods: {
    getOneOrgUsers() {
      getOneOrgUsers({ pageNumber: 1, pageSize: 999999, rootOrgId:  this.projectOrgId,queryPost: false }).then(res=>{
        this.userList = res.data.list || []
      })
    },
    //所属单位
    selectOrg(val) {
      if(val&&val.length) { 
        this.form.projectDeptId = val[val.length - 2].orgId
        this.projectOrgId = val[val.length - 1].orgId
        this.getProjectInfo(this.form.projectId)
        this.getOneOrgUsers()
      }
    },
    // 计算第一个表的和
    changeTable1(record) {
      record.notContractFee = record.notContractFee ? record.notContractFee : 0
      record.contractFeeRate = record.contractFeeRate ? record.contractFeeRate : 0
      record.contractFee = record.notContractFee + record.contractFeeRate
    },
    //  ['autoContractFee', 'notAutoContractFee', 'autoContractFeeRate']"
    changeTable2(record) {
      record.notAutoContractFee = record.notAutoContractFee ? record.notAutoContractFee : 0
      record.autoContractFeeRate = record.autoContractFeeRate ? record.autoContractFeeRate : 0
      record.autoContractFee = (record.notAutoContractFee + record.autoContractFeeRate).toFixed(2)
      this.changeForm('autoContractFee')
    },
    changeForm(key) {
      if (
        (key == 'tentativelyUpProfitFee' || key == 'autoContractFee') &&
        (this.form.tentativelyUpProfitFee || this.form.tentativelyUpProfitFee == 0) &&
        (this.loadData2[0].autoContractFee || this.loadData2[0].autoContractFee == 0)
      ) {
        this.form.tentativelyUpRate = isNaN(
          (((this.form.tentativelyUpProfitFee * 10000) / this.loadData2[0].autoContractFee) * 100).toFixed(2)
        )
          ? undefined
          : (((this.form.tentativelyUpProfitFee * 10000) / this.loadData2[0].autoContractFee) * 100).toFixed(2)
      } else {
        this.form.tentativelyUpRate = 0
      }
    },
    personChanged(e, record) {
      if (e && Object.keys(e).length) {
        record.code = e.jobNum
        record.nameText = e.name
        record.idCard = e.idCard
        // this.$refs.tableRisk.refresh(true)
      }
    },
    print() {
      return printTarget({ id: this.id }).then((res) => {
        return res[1].data.content
      })
    },
    /**
     * 获取项目信息
     */
    getProjectInfo(projectId) {
      let data = {
        projectId: projectId
      }
      getProjectInfo(data).then((res) => {
        this.$nextTick(() => {
          this.winTheBidTime = res.data.winningTime
          this.form.completeTime = res.data.startWorkingTime
            ? moment(res.data.startWorkingTime).add(2, 'months').format('YYYY-MM-DD')
            : res.data.startWorkingTime

          this.form.projectManagerName = res.data.projectManagerName
          // 判断是否添加了标价分离书，需审批完成，才能添加目标责任书。如标价分离书未审批完成，则报错提示：标价分离书添加并审核通过，才可添加目标责任书。
          // 如继续添加则不可提交。
          if (res.data.contractModelCode != 'gczcb_sgdwqt' && res.data.contractModelCode != 'gczcb_sjdwqt') {
            this.getQuotationList(projectId)
          }
          // 1个项目只会有1个目标责任书
          this.editModel == 2 && this.getTargetList(projectId)
        })
      })
    },
    async getQuotationList(projectId) {
      const [err, res] = await getQuotationList({ projectId: projectId })

      if (!err) {
        if (res.data.filter((i) => i.auditStatus == 'PAST').length == 0) {
          this.isAdd = true
          this.$message.warning('标价分离书添加并审核通过，才可添加目标责任书')
        }
      }
    },
    async getTargetList(projectId) {
      const [err, res] = await getTargetList({ projectId: projectId })
      if (!err) {
        if (res.data.filter((i) => i.status == 'SUBMITTED' || i.status == 'PAST').length > 0) {
          this.isAdd = true
          this.$message.warning('该项目已有一个目标责任书')
        }
      }
    },

    change(col) {
      if (col == 'planRiskFee') {
        this.form.reservedRiskFee = 0
        this.form.riskFeeData.forEach((item) => {
          this.$nextTick(() => {
            if (parseFloat(item.planRiskFee) || parseFloat(item.planRiskFee) == 0) {
              this.form.reservedRiskFee += parseFloat(item.planRiskFee)
            }
          })
        })
        this.$refs.tableRisk.refresh(true)
      }
    },
    /**
     * 导出
     */
    exportAll() {
      const flag = false
      this.form.riskFeeData.forEach((item) => {
        if (!item.name) {
          this.$message.warning('请完善人员选择后导出')
          flag = true
        }
      })
      if (flag) return
      this.$refs.exportAll.setDataAndGenerate(this.form.riskFeeData)
    },
    /**
     * @description: 批量导入
     * @param {Array} data：导入列表
     */
    async handleImport(e) {
      let form = []

      // 遍历校验表格字段，且添加表单
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!Object.keys(keys).includes(i) && item !== 'remark') {
            this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
            return
          } else {
            // // 培训类别格式化

            if ((item === 'riskRate' || item === 'planRiskFee') && isNaN(keys[i])) {
              console.log(typeof keys[i])

              this.$message.warning(`第${Number(index) + 1}行${i}必须为数字`)
              return
            } else {
              listItem[item] = keys[i]
            }
          }
        }
      }

      for (let index in this.form.riskFeeData) {
        let i = this.form.riskFeeData[index]
        for (let item of form) {
          if (i.nameText == item.nameText) {
            item.name = i.name
            item.code = i.code
            item.idCard = i.idCard
            this.form.riskFeeData[index] = this.$clone(item)
            console.log(i)
          }
        }
      }

      this.change('planRiskFee')
      this.$refs.tableRisk.refresh(true)
    },

    del(data, idx) {
      this.form.riskFeeData.splice(idx, 1)
      this.change('planRiskFee')
      this.$refs.tableRisk.refresh(true)
    },
    //添加行
    addLine() {
      this.form.riskFeeData.push({
        name: undefined,
        idCard: undefined,
        planRiskFee: undefined,
        remark: undefined,
        riskRate: undefined,
        code: undefined
      })

      this.$refs.tableRisk.refresh()
    },
    validateTable() {
      let flag = false
      if (this.form.riskFeeData.length == 0) {
        this.$message.warning('请添加风险金分配表')
        flag = true
      }
      this.form.riskFeeData.forEach((item) => {
        if (!item.name && !item.planRiskFee && !item.riskRate) {
          this.$message.warning('请完善表格后提交')
          flag = true
        }
      })
      return flag
    },
    validateForm() {
      let flag = false
      if (this.loadData1[0].notContractFee == undefined || this.loadData1[0].notContractFee == null) {
        this.$message.warning('请输入合同额不含税')

        return false
      }
      if (this.loadData1[0].contractFeeRate == undefined || this.loadData1[0].contractFeeRate == null) {
        this.$message.warning('请输入合同额税金')
        return false
      }
      if (this.loadData2[0].notAutoContractFee == undefined || this.loadData2[0].notAutoContractFee == null) {
        this.$message.warning('请输入自施合同额不含税')
        return false
      }
      if (this.loadData2[0].autoContractFeeRate == undefined || this.loadData2[0].autoContractFeeRate == null) {
        this.$message.warning('请输入自施合同额税金')
        return false
      }

      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }
      })
      return flag
    },
    /**
     * 提交表单
     */
    handleSave(status) {
      this.setProcessConfig = null;   
      if (status == 'SUBMITTED') {
        // 校验表单
        if (!this.validateForm() && this.validateTable()) {
          return
        }
      }
      // 表格数据添加到form
      this.form.notContractFee = this.loadData1[0].notContractFee
      this.form.contractFeeRate = this.loadData1[0].contractFeeRate
      this.form.contractFee = this.loadData1[0].contractFee
      this.form.notAutoContractFee = this.loadData2[0].notAutoContractFee
      this.form.autoContractFeeRate = this.loadData2[0].autoContractFeeRate
      this.form.autoContractFee = this.loadData2[0].autoContractFee
      console.log(this.form)
      this.loading = true
      this.loadingBtn[status] = true
      this.form.status = status
      let form = this.$clone(this.form)
      form.riskFeeData?.forEach((i) => {
        delete i.id
      })
      addTarget(form).then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          if(res[1].code== 200){
            this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
            if(status =='SUBMITTED') {
                //提交时，返回id
                    this.businessId = res[1].data || this.id;
                    this.setProcessConfig = this.processConfig;
                    return
                }else{
                  this.$multiTab.close()
              }
          }
        
        })
        .catch((e) => {
          console.log(e)
          this.loadingBtn[status] = false
          this.loading = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  /*.ant-input:not([disabled]),*/
  /*.ant-select:not(.ant-select-disabled) .ant-select-selection,*/
  /*.ant-calendar-picker-input,*/
  /*.ant-input-number:not([disabled]),*/
  /*.ant-cascader-picker {*/
  /*  border-color: #e4ac0b;*/
  /*  background-color: #fff9e8;*/
  /*}*/
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
// /deep/ .ant-form-item {
//     .ant-form-item-label {
//         height: 28px;
//         width: 200px;
//         line-height: 22px;
//         padding: 6px 4px 0 0;
//         text-align: right;
//         white-space: pre-wrap;
//         overflow: visible;
//     }
//     .ant-form-item-control-wrapper {
//         width: calc(100% - 200px);
//     }
// }
.file_prompt {
  color: #999;
}
.tip {
  color: #1890ff;
  font-size: 16px;
  margin-bottom: 12px;
}
</style>
